import type { AxiosError, AxiosInstance, AxiosResponse } from 'axios';
import axios from 'axios';
import { ElNotification } from 'element-plus';

/** 约定前后端交互格式 */
export interface ResponseType {
  code: number;
  message: string;
  data?: ResponseDataType;
}

export type ResponseDataType = {
  [key: string]: any
}

/** 配置axios实例 */
const service: AxiosInstance = axios.create({
  baseURL: 'https://www.demo.com',
  timeout: 5000,
});

/** 配置请求拦截器 */
service.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    // 提示错误信息
    ElNotification({
      title: 'Error',
      type: 'error',
      message: `Request Error: ${error.message}`,
    });
    return Promise.reject(error);
  }
);

/** 配置响应拦截器 */
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data;
    if (res.code !== 200) {
      ElNotification({
        title: 'Error',
        type: 'error',
        message: res.message || 'Error',
      });
      return Promise.reject(new Error(res.message || 'Error'));
    }

    return res.data;
  },
  (error: AxiosError) => {
    // 提示错误信息
    ElNotification({
      title: 'Error',
      type: 'error',
      message: `Response Error: ${error.message}`,
    });
    return Promise.reject(error);
  }
);

export default service;
